#include "myinet.h"
#include "tools.h"

// a tcp server that echos whatever it received
// run this with the following command
// ./echoserver <port-number>

int 
main(int argc, char** argv){
    int portNumber;
    int sockfd, newsock;
    socklen_t clilen;
    struct sockaddr_in clisockaddr;

    if (argc != 2){
        printf("usage: %s <port number>\n", argv[0]);
        error_exit("specify the port number", NULL);
    }

    portNumber = atoi(argv[1]);
    printf("port number : %d", atoi(argv[1]));

    info("getting socket");
    sockfd = getTcpServerSocket(portNumber);

    if (sockfd < 0){
        error_exit("ERROR creating socket", "socket");
    }

    debug("got socket");

    clilen = sizeof(clisockaddr);
    printf("waiting for connection on port: %d\n", portNumber);
    newsock = accept(sockfd, (struct sockaddr*)&clisockaddr, &clilen);

    info("got one request from %s:%d", inet_ntoa(clisockaddr.sin_addr),
            ntohs(clisockaddr.sin_port));

    if (newsock < 0){
        error_exit("accept", 0);
    }

    char buf[256];
    int n = 0;
    while ((n = read(newsock, buf, sizeof(buf))) > 0){
        // write back what the server received
        write(newsock, buf, n);
        info("received: %s", buf);
        if (strcmp(buf, "bye") == 0)
            break;
    }


}
